import {number} from './number.js'
import {strFrom, strTo} from './str.js'

const _css_camelize = (function() {
	let b = {'float' : 'cssFloat'}
	return function(s) {
		return b[s] || s.replace(/-./g, function($0) {return $0.charAt(1).toUpperCase()});
	}
})()

// @o -> el, n -> name, v -> value
const _set_style = function(o, n, v) {
	// 如属性名前面带 += 号，则执行 += 操作
	if (typeof v === 'string' && v.charAt(1) === '=') {
		var	n = _css_camelize(n),
			c = o.style[n] || getComputedStyle(o, null)[n],
			v = number(v.replace('=', ''))
		if (n === 'width' || n === 'height') {
			c = number(c && c !== 'auto' ? c : n.charAt(0) === 'w' ? o.offsetWidth : o.offsetHeight);
			if (c < 0) c = 0;
		} else
			c = number(c);
		o.style[n] = (c + v) + (n === 'zIndex' ? 0 : 'px');
	} else {
		n = _css_camelize(n);
		if (n === 'width' || n === 'height')
			v && v !== 'auto' && (v = Math.max(_number(v), 0));
		if (v && !isNaN(v) && n !== 'zIndex')
			v += 'px';
		o.style[n] = v;
	}
	return o;
}

const css = function(o, s, n) {
	if (!o || !s)
		return null;
	if (n != null) {
		for (var i = 1, l = arguments.length; i < l; i += 2)
			_set_style(o, arguments[i], arguments[i + 1]);
	} else {
		if (typeof s === 'string') {
			if (s.indexOf(':') > 0) {
				for (var i = 0, b = s.split(';'), l = b.length, k, v; i < l; i ++)
					(k = strTo(b[i], ':')) && (v = strFrom(b[i], ':')) && _set_style(o, k, v);
			} else
				return o.style[s] || getComputedStyle(o, null)[s];
		}
		for (var i in s) _set_style(o, i, s[i]);
	}
}

export {css}